// redux新版本中的slice.其实就是reducer和actions的集合体
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// 创建异步对象.这个对象有两个作用: 1. 相当于就是一个异步action 2. 可以监听返回的promise的状态
export const asyncCount = createAsyncThunk('yyy', () => {
  return new Promise((resolve, reject) => {
    //这里执行异步操作
    setTimeout(() => {
      //   resolve(5)
      reject()
    }, 2000)
  })
})
const countSlice = createSlice({
  name: 'xxx', // slice的名字
  initialState: { count: 0, msg: 'hello' },
  reducers: {
    add(state, action) {
      // 注意: 这个state不是真实store数据,而是store数据的代理.所以可以直接修改
      console.log(action)
      state.count = state.count + action.payload
    },
  },

  // 配置异步操作
  extraReducers(builder) {
    builder.addCase(asyncCount.pending, (state, action) => {
      console.log('异步开始执行了')
    })
    builder.addCase(asyncCount.fulfilled, (state, action) => {
      console.log('异步成功了')
      state.count = state.count + action.payload
    })
    builder.addCase(asyncCount.rejected, (state, action) => {
      console.log('异步失败了')
    })
  },
})

export default countSlice
